package com.aliyun.order.server.config;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.aliyun.commons.service.SendMessageService;
import com.aliyun.commons.service.impl.SendMessageServiceImpl;
import com.aliyun.order.server.service.message.LocalTransactionChecker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 消息配置
 *
 * 
 * @date 2024/12/01
 */
@Slf4j
@Configuration
public class MessageConfig {

    /**
     * 发送消息服务
     *
     * @param username
     * @param password 密码
     * @param endpoint 端点
     * @return {@link SendMessageService }
     */
    @Bean
    public SendMessageService sendMessageService(@Value("${rocketmq.username}") String username,
        @Value("${rocketmq.password}") String password, @Value("${rocketmq.endpoint}") String endpoint,
        @Value("${rocketmq.order-fail-after-deducted-inventory-topic}") String failTopic,
        @Value("${rocketmq.order-success-topic}") String successTopic,
        @Autowired List<LocalTransactionChecker> checkers) {
        Map<String, LocalTransactionChecker> transactionCheckerMap = checkers.stream().collect(
            Collectors.toMap(LocalTransactionChecker::getTopic, Function.identity()));
        return new SendMessageServiceImpl(username, password, endpoint, Arrays.asList(failTopic, successTopic),
            view -> {
                log.info("Receive transactional message check, message={}", view);
                return transactionCheckerMap.get(view.getTopic()).check(view);
            });
    }
}
